package com.ycp.erp.login.presenter;

import android.content.Context;

import com.one.common.common.system.SystemModel;
import com.one.common.common.system.model.response.SessionResponse;
import com.one.common.common.system.model.response.UserInfoResponse;
import com.one.common.config.CMemoryData;
import com.one.common.config.CPersisData;
import com.one.common.config.RouterPath;
import com.one.common.manager.RouterManager;
import com.one.common.model.http.ErrorConstant;
import com.one.common.model.http.callback.ObserverOnNextListener;
import com.one.common.presenter.BaseApiPresenter;
import com.one.common.utils.ApplyUtils;
import com.one.common.utils.ResourceUtils;
import com.one.common.utils.Toaster;
import com.one.common.view.base.BaseActivity;
import com.one.common.view.dialog.AutoDialogHelper;
import com.ycp.erp.R;
import com.ycp.erp.login.mobel.LoginModel;
import com.ycp.erp.login.mobel.param.LocationParam;
import com.ycp.erp.login.mobel.param.LoginParam;
import com.ycp.erp.login.mobel.param.SendCodeParam;
import com.ycp.erp.login.mobel.response.DefaultResponse;
import com.ycp.erp.login.view.SendCodeView;

/**
 * Author: zhulunjun
 * Email: zhulunjun@qq.com
 * CreateDate: 2018/11/15 19:17
 * Description：
 **/
public class LoginPresenter extends BaseApiPresenter<SendCodeView, LoginModel>  {
    /**
     * 定位相关信息
     */
    private LocationParam locationParam;

    public LoginPresenter(SendCodeView mView, Context mContext) {
        super(mView, mContext, new LoginModel((BaseActivity) mContext));
    }

    @Override
    public void onCreate() {
        super.onCreate();
//        if (!(mActivity instanceof LoadingActivity)) {
//            location();
//        }

//        if (mActivity instanceof LoginActivity) {
//            new UpdateModel(mActivity).updateVersion(firUpdateResponse -> {
//                new UpdateDialog(mActivity, firUpdateResponse).show();
//            });
//        }

    }

    /**
     * 定位
     */
//    private void location() {
//        LocationUtils.location(mActivity, this);
//    }


    /**
     * 发生验证码
     */
    public void sendCode(String phone, String type) {
        if (!ApplyUtils.validateMobile(phone)) {
            Toaster.showLongToast(ResourceUtils.getString(com.one.common.R.string.phone_format_error));
            return;
        }
        if (mView == null) return;
        mView.showLoading();
        CMemoryData.setUserMobile(phone);
        new SystemModel().getSession(new ObserverOnNextListener<SessionResponse>() {
            @Override
            public void onNext(SessionResponse sessionResponse) {
                CMemoryData.setSessionId(sessionResponse.getSession_id());


                mModel.sendCode(phone, type, new ObserverOnNextListener<DefaultResponse>() {
                    @Override
                    public void onNext(DefaultResponse sendCodeResponse) {
                        if (mView == null) return;
                        if (sendCodeResponse.getResult_code()) {
                            Toaster.showLongToast(com.one.common.R.string.verify_send_success);
                            mView.startCountDown();
                        } else {
                            Toaster.showLongToast(com.one.common.R.string.verify_send_fail);
                            mView.resetCountDown();
                        }
                    }

                    @Override
                    public void onError(String errorCode, String msg) {
                        if (mView == null) return;
                        mView.resetCountDown();
                        Toaster.showLongToast(msg + "");
                    }
                });
            }

            @Override
            public void onError(String errorCode, String msg) {
                Toaster.showLongToast(msg);
            }
        });

    }


    public void sendCodeModifyPhone(String phone, String type) {
        if (!ApplyUtils.validateMobile(phone)) {
            Toaster.showLongToast(ResourceUtils.getString(com.one.common.R.string.phone_format_error));
            return;
        }
        if (mView == null) return;
        mView.showLoading();

        mModel.sendCode(phone, type, new ObserverOnNextListener<DefaultResponse>() {
            @Override
            public void onNext(DefaultResponse sendCodeResponse) {
                if (mView == null) return;
                if (sendCodeResponse.getResult_code()) {
                    Toaster.showLongToast(com.one.common.R.string.verify_send_success);
                    mView.startCountDown();
                } else {
                    Toaster.showLongToast(com.one.common.R.string.verify_send_fail);
                    mView.resetCountDown();
                }
            }

            @Override
            public void onError(String errorCode, String msg) {
                if (mView == null) return;
                mView.resetCountDown();
                Toaster.showLongToast(msg + "");
            }
        });

    }


    /**
     * 密码登录
     */
    public void loginPwd(String phone, String pwd) {
        login(phone, pwd, LoginParam.TYPE_PWD);

    }

    /**
     * 验证码登录
     */
    public void loginVerify(String phone, String code) {
        login(phone, code, LoginParam.TYPE_VERIFY);
    }


    public void modifyPhohe(String phone, String code) {
        mModel.modifyPhone(phone, code, sendCodeResponse -> {
            if (sendCodeResponse.isSuccess()) {
                CMemoryData.setUserMobile(phone);
                Toaster.showLongToast("修改成功");
                mView.finishPage();
            } else {
                Toaster.showLongToast(sendCodeResponse.getMessage() + "");
            }
        });
    }

    /**
     * 登录
     */
    private void login(String phone, String pwd, String type) {
        if (mView == null) return;
        mView.showLoading();
        CMemoryData.setUserMobile(phone);
        new SystemModel().getSession(new ObserverOnNextListener<SessionResponse>() {
            @Override
            public void onNext(SessionResponse sessionResponse) {
                CMemoryData.setSessionId(sessionResponse.getSession_id());
                mModel.login(phone, pwd, type, locationParam, new ObserverOnNextListener<UserInfoResponse>() {
                    @Override
                    public void onNext(UserInfoResponse userInfoResponse) {
                        if (userInfoResponse != null) {
                            loginAndRegisterSuccess(userInfoResponse, phone, false);
                            Toaster.showLongToast(R.string.login_success);
                        }
                    }

                    @Override
                    public void onError(String errorCode, String msg) {
                        // 没注册
                        if (errorCode.equals(ErrorConstant.NOT_REGISTER)) {
                            notRegister();
                            // 新设备
                        } else if (errorCode.equals(ErrorConstant.NEW_DEVICE) || errorCode.equals(ErrorConstant.NEW_DEVICE_1)) {
                            Toaster.showLongToast(msg);
                            if (mView != null) {
                                mView.startCountDown();
                                sendCode(phone, SendCodeParam.TYPE_LOGIN);
                            }
                        } else {
                            Toaster.showLongToast(msg);
                        }
                    }
                });
            }

            @Override
            public void onError(String errorCode, String msg) {
                Toaster.showLongToast(msg);
            }
        });

    }

//    /**
//     * 注册
//     */
//    public void register(String phone, String pwd, String code, String inviteCode, String truckerType) {
//        if (!checkRegisterInfo(phone, pwd, code, inviteCode)) return;
//        mModel.register(phone, pwd, code, inviteCode, locationParam, truckerType, userInfoResponse -> {
//            if (userInfoResponse != null) {
//                loginAndRegisterSuccess(userInfoResponse, phone, true);
//                Toaster.showLongToast(R.string.register_success);
//            }
//        });
//    }

    /**
     * 注册和登陆成功后的处理
     */
    private void loginAndRegisterSuccess(UserInfoResponse userInfo, String mobile, boolean isRegister) {
        CMemoryData.setUserInfo(userInfo);
        CMemoryData.setUserMobile(mobile);
        /** 设置用户登录过，可以复用sessionId */
        CPersisData.setIsLogin(true);
        // 显示设置密码弹窗
        CPersisData.setIsSetPwd(true);

//        //这边判断 批量车主身份，是否设置密码
//        if (CMemoryData.getAppSorce().equals(MyContact.CAR) && "0".equals(userInfo.getPwdBlank())) {
//            RouterManager.getInstance().go(RouterPath.SET_PWD, new SetPwdExtra(SetPwdExtra.TYPE_lOT_SIZE));
//        } else {
//            RouterManager.getInstance().goAndFinish(mActivity, RouterPath.MAIN_PAGE, new DefaultExtra(isRegister));
//        }
    }
//
//    /**
//     * 检查验证码(找回密码)
//     */
//    public void checkCode(String phone, String code) {
//        if (!ApplyUtils.validateMobile(phone)) return;
//        mModel.checkCode(phone, code, sendCodeResponse -> {
//            RouterManager.getInstance().go(RouterPath.SET_PWD, new SetPwdExtra(SetPwdExtra.TYPE_FORGET));
//        });
//    }
//
//    /**
//     * 设置密码
//     */
//    public void setPwd(String pwd, String pwdc) {
//        if (!checkNewPwd(pwd, pwdc)) return;
//        if (!ApplyUtils.validatePassword(pwd)) return;
//        mModel.setPwd(CMemoryData.getUserMobile(), pwd, sendCodeResponse -> {
//            RouterManager.getInstance().go(RouterPath.LOGIN_PAGE);
//            Toaster.showLongToast(com.one.common.R.string.update_pwd_success);
//        });
//
//    }
//
//    public void toSetPwd(String pwd) {
//        if (!ApplyUtils.validatePassword(pwd)) return;
//        mModel.setPwd(CMemoryData.getUserMobile(), pwd, sendCodeResponse -> {
//            Toaster.showLongToast(com.one.common.R.string.set_pwd_success);
//
//            //这边判断 ： 属于批量注册用户 并且未确认的用户 ----  跳转到确认页面
//            RouterManager.getInstance().goAndFinish(mActivity, RouterPath.LOTSIZE_AUTH_CONFIRM);
//        });
//
//    }
//
//    /**
//     * 验证旧密码
//     */
//    public void checkOldPwd(String pwd) {
//        mModel.checkOldPwd(pwd, sendCodeResponse -> {
//            if (sendCodeResponse.isSuccess()) {
//                RouterManager.getInstance().go(RouterPath.SET_PWD, new SetPwdExtra(SetPwdExtra.TYPE_SET));
//            } else {
//                Toaster.showLongToast("旧密码错误");
//            }
//        });
//
//    }
//
//
//    /**
//     * 验证两次密码是否一致
//     */
//    private boolean checkNewPwd(String pwdc, String pwd) {
//        if (!pwdc.equals(pwd)) {
//            Toaster.showLongToast(com.one.common.R.string.pwd_not_same);
//            return false;
//        }
//        return true;
//    }
//
//
//    /**
//     * 没有注册
//     */
    private void notRegister() {
        AutoDialogHelper.showContent(mActivity, "您输入的手机号尚未注册， 是否前去注册？",
                "取消", "立即注册", () -> RouterManager.getInstance().go(RouterPath.REGISTER));
    }
//
//
//    @Override
//    public void onLocated(AMapLocation aMapLocation) {
//        if (aMapLocation != null) {
//            locationParam = new LocationParam();
//            locationParam.setLogin_address(aMapLocation.getAddress());
//            locationParam.setLogin_city_id(aMapLocation.getAdCode());
//            locationParam.setLogin_latitude(aMapLocation.getLatitude() + "");
//            locationParam.setLogin_longitude(aMapLocation.getLongitude() + "");
//        }
//    }
//
//    @Override
//    public void onLocationPermissionfaild() {
//        // 定位失败这里不处理
//    }
//
//    /**
//     * 获取用户状态
//     */
//    public void getUserState() {
//        new UserModel(mActivity).getUserState(userStateResponse -> {
//            if (userStateResponse != null) {
//                BusManager.getBus().post(new UserStateEvent(userStateResponse));
//                CMemoryData.setUserState(userStateResponse);
//                // 消息
//                BusManager.getBus().post(new MessageEvent(userStateResponse));
//            }
//
//        });
//    }
}
